package team.archai.nexus.boot.tool;

import org.apache.commons.codec.binary.Hex;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.util.logging.Logger;

/**
 * @program: MD5Utils
 * @description: MD5加密工具类
 * @author: lishibin
 * @create: 3:26 PM
 **/
public class MD5Utils {

    private static Logger log = Logger.getLogger(MD5Utils.class.getName());

    /**
     * @program: MD5Utils
     * @description: 計算文件的MD5
     * @author: lishibin
     * @create: 9:24
     **/
    public static String getMD5(File file) {
        FileInputStream fileInputStream = null;
        try {
            MessageDigest MD5 = MessageDigest.getInstance("MD5");
            fileInputStream = new FileInputStream(file);
            byte[] buffer = new byte[8192];
            int length;
            while ((length = fileInputStream.read(buffer)) != -1) {
                MD5.update(buffer, 0, length);
            }
            return new String(Hex.encodeHex(MD5.digest()));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
            } catch (IOException e) {
                log.info(e.getMessage());
            }
        }
    }
}
